//
//  YLMessageCenterViewModel.m
//  YLFinanceService
//
//  Created by she1323 on 2017/10/18.
//  Copyright © 2017年 she1323. All rights reserved.
//

#import "YLMessageCenterViewModel.h"
#import "WHNetworkTool.h"
#import "YLAccountTool.h"
#import "YLMessageCenterGroup.h"
#import "WHProgressHUD.h"
@implementation YLMessageCenterViewModel

- (instancetype)initWithIsLoop:(NSInteger)loop
{
    if (self = [super init]) {
        [self setUpWithLoop:loop];
    }
    return self;
}

- (void)setUpWithLoop:(NSInteger)loop
{
    __weak typeof(self) weakSelf = self;
    _requestCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal * _Nonnull(id  _Nullable input) {
        return [RACSignal createSignal:^RACDisposable * _Nullable(id<RACSubscriber>  _Nonnull subscriber) {
            
            [WHProgressHUD showStatus:@"数据加载中..."];
            NSDictionary *params = @{@"IsLoop" : @(loop)};
            
            NSString *url = [NSString stringWithFormat:@"%@AppCommon/PGetNoticeList", YLURL];
            
            [[WHNetworkTool shareInstance] sendPostWithUrl:url header:[YLAccountTool header] params:params success:^(id responseObject) {
                NSLog(@"%@", responseObject);
                [WHProgressHUD dismiss];
                if ([responseObject[@"httpCode"] integerValue] == 200) {
                    YLMessageCenterGroup *group = [YLMessageCenterGroup yy_modelWithDictionary:responseObject[@"httpResult"]];
                    [weakSelf.models addObjectsFromArray:group.item];
                    [subscriber sendNext:nil];
                } else {
                    [WHProgressHUD showError:responseObject[@"message"]];
                }
                
                [subscriber sendCompleted];
            } fail:^(NSError *error) {
                [subscriber sendCompleted];
            }];
      
            return nil;
        }];
    }];
}

- (void)dealloc
{
    [WHProgressHUD dismiss];
    [[WHNetworkTool shareInstance] cancel];
}

- (NSMutableArray<YLMessageCenterModel *> *)models
{
    if (!_models) {
        _models = [NSMutableArray array];
    }
    return _models;
}
@end
